<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/20
 * Time: 下午9:40
 */

namespace common\logic;


use common\models\BaseHouseMarkModel;
use common\models\BaseHouseTypeModel;
use common\models\BaseUnitPriceModel;
use common\models\FavoriteModel;
use common\models\HouseModel;
use common\models\BaseRegionModel;
use common\models\HouseMarkModel;
use common\models\MessageModel;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

class HouseLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return HouseModel::find();
    }

    public function getAll($ids){
        return $this->_all(['id'=>$ids]);
    }

    public function getHouseDetail($id,$uid='0')
    {
        $house = $this->getById($id);
        $has_attention=0;
        if(!empty($uid)&&FavoriteModel::findOne(["house_id"=>$id,"uid"=>$uid])){
            $has_attention=1;
        }

        if (empty($house)) {
            return false;
        }

        $images = HouseImageLogic::instance()->getAll($id);
        $newImages = [];
        if (!empty($images)) {
            foreach ($images as $image) {
                $newImages[] = $image->img_path;
            }
        }

        if (!empty($house->decoration_id)) {
            $decoration = DecorationTypeLogic::instance()->get($house->decoration_id);
        }
        if (!empty($house->region_id)) {
            $region = RegionLogic::instance()->getById($house->region_id);
            //$region->parent_name=RegionLogic::instance()->getById($region->id);
//            echo var_dump($region);
        }
        if (!empty($house->category_id)) {
            $category = HouseCategoryLogic::instance()->getById($house->category_id);
        }

        $houseTypeImage = HouseTypeImageLogic::instance()->getAll($house->id);
        $house_state_info=MessageModel::find()->select('id,title,content,create_at')->where(['hid'=>$id])->orderBy(['id'=>SORT_DESC])->limit(5)->all();
        

        $newHouseTypeImage = [];
        if (!empty($houseTypeImage)) {
            foreach ($houseTypeImage as $item) {
                $typeimg = HouseTypeImglistLogic::instance()->getAll($item->id);
                $item = $item->toArray(['img_path', 'name', 'area', 'price', 'house_type']);
                $item['typeimg'] = $typeimg;
                $newHouseTypeImage[] = $item;
            }
        }

        $result = $house->toArray(['house_name', 'house_unit_price', 'return_money', 'developer', 'checkout', 'property', 
        'house_area','floor_area','area_covered', 'total_price', 'address', 'room1', 'room2', 'head', 'phone', 'plot_ratio', 
        'greening_rate', 'layout_number', 'car_number', 'building_type', 'property_fee', 'property_company','discount_1',
        'discount_2','return_day','payment_rate','region_id','latitude','longitude']);

        $result['decoration'] = empty($decoration) ? '' : $decoration->decoration_type;
        $result['region'] = empty($region) ? '' :  $region->region_name;
        $result['category'] = empty($category) ? '' : $category->category;
        $result['images'] = $newImages;
        $result['houseTypeImage'] = $newHouseTypeImage;
        $result['has_attention']=$has_attention;
        $result['state_info']=$house_state_info;
		$result['mark']=$this->getHouseMarks($id);
        return ['house' => $result];
    }

    public function getAdv()
    {
        /**
         * @var $banners HouseModel[]
         */
        $banners = $this->getQuery(['is_banner_home' => 1], [], ['id','banner'], ['id' => SORT_DESC])->andWhere("banner>''")->limit(6)->all();
        $newBanners = [];
        foreach ($banners as $banner) {
            $newBanners[] = ["id"=>$banner->id,"banner"=>$banner->banner];
        }
        /**
         * @var $adv HouseModel
         */
        $adv = $this->getQuery(['is_adv' => 1], [], ['id','adv'], ['id' => SORT_DESC])->andWhere("adv>''")->limit(1)->one();
        $newAdv = '';
        if (!empty($adv)) {
            $newAdv =["id"=>$adv->id,"adv"=>$adv->adv];
        }

        return ['banners' => $newBanners, 'adv' => $newAdv];
    }

    public function getListBanner()
    {
        /**
         * @var $banners HouseModel[]
         */
        $banners = $this->getQuery(['is_banner' => 1], [], ['id','banner'], ['id' => SORT_DESC])->andWhere("banner>''")->limit(6)->all();
        $newBanners = [];
        foreach ($banners as $banner) {
            $newBanners[] = ["id"=>$banner->id,"banner"=>$banner->banner];
        }

        return ['banners' => $newBanners];
    }



    /**
     * @param $id
     *
     * @return array|null|HouseModel
     */
    protected function getById($id)
    {
        return $this->_get(['id' => $id]);
    }

    /**
     * 推荐楼盘
     *
     * @return array
     */
    public function getRecommend()
    {

        //上海楼盘
        $query = $this->_getActiveQuery();
        $query = $query->select(['a.id','a.region_id', 'house_name','c.region_name as parent_region','a.address','b.region_name', 'house_unit_price','return_money', 'house_area', 'total_price', 'room1', 'room2'])->alias('a')->leftJoin('ph_base_region b','a.region_id=b.id')->leftJoin('ph_base_region c','b.parent=c.id')->limit(5)->orderBy(['is_recommend'=>SORT_DESC,'recommend_sort' => SORT_DESC,'a.id' => SORT_DESC]);
        $data_sh = $query->asArray()->all();

        if (!empty($data_sh)) {
            $hourseIds = ArrayHelper::getColumn($data_sh, 'id');
            $images = HouseImageLogic::instance()->getFirstImage($hourseIds);

            foreach ($data_sh as $k => $v) {
                $v['marks']=$this->getHouseMarks($v['id']);
                $v['img_path'] = empty($images[$v['id']]) ? '' : $images[$v['id']];
                $data_sh[$k] = $v;
            }

        }


        //海外楼盘
        $query = $this->_getActiveQuery();
        $query = $query->select(['a.id','a.region_id', 'house_name','c.region_name as parent_region','a.address',
        'b.region_name', 'house_unit_price','return_money', 'house_area', 'total_price', 'room1', 'room2'])
        ->alias('a')->leftJoin('ph_base_region b','a.region_id=b.id')->leftJoin('ph_base_region c','b.parent=c.id')
        ->where(['b.parent'=>123])->limit(5)->orderBy(['is_recommend'=>SORT_DESC,'recommend_sort' => SORT_DESC,'a.id' => SORT_DESC]);
        $data_hw = $query->asArray()->all();

        if (!empty($data_hw)) {
            $hourseIds = ArrayHelper::getColumn($data_hw, 'id');
            $images = HouseImageLogic::instance()->getFirstImage($hourseIds);

            foreach ($data_hw as $k => $v) {
                $v['marks']=$this->getHouseMarks($v['id']);
                $v['img_path'] = empty($images[$v['id']]) ? '' : $images[$v['id']];
                $data_hw[$k] = $v;
            }

        }

        return ['list_sh' => $data_sh,'list_hw' => $data_hw];
    }

    /**
     * 同区域的楼盘推荐
     *
     * @return array
     */
    public function getSameRegionHouse($region_id)
    {

        $query = $this->_getActiveQuery();
        $query = $query->select(['a.id','a.region_id', 'house_name','c.region_name as parent_region','a.address','b.region_name', 'house_unit_price','return_money', 'house_area', 'total_price', 'room1', 'room2'])->alias('a')->leftJoin('ph_base_region b','a.region_id=b.id')->leftJoin('ph_base_region c','b.parent=c.id')->where(['a.region_id'=>$region_id])->limit(5)->orderBy(['a.id' => SORT_DESC]);
        $data = $query->asArray()->all();

        if (!empty($data)) {
            $hourseIds = ArrayHelper::getColumn($data, 'id');
            $images = HouseImageLogic::instance()->getFirstImage($hourseIds);

            foreach ($data as $k => $v) {
                $v['marks']=$this->getHouseMarks($v['id']);
                $v['img_path'] = empty($images[$v['id']]) ? '' : $images[$v['id']];
                $data[$k] = $v;
            }

        }

        return ['list' => $data];
    }

    /**
     * 分页
     *
     * @param        $page
     * @param int    $pageSize
     * @param array  $search
     *
     * @return array
     */
    public function getByPage($page, $pageSize = 20, $search = [])
    {
        $nextPage = 0;
        $query = $this->_getActiveQuery();
		$queryNum = $this->_getActiveQuery();
		
        $offset = ($page - 1) * $pageSize;
        $query = $query->select(['id', 'house_name', 'house_unit_price', 'return_money', 'house_area', 'total_price', 'address', 'room1', 
        'room2','region_id'])->limit($pageSize + 1)->offset($offset)->orderBy(['is_recommend'=>SORT_DESC,'recommend_sort' => SORT_DESC,'id' => SORT_DESC]);
		
		$queryNum = $queryNum->select(['id']);
		
		if (!empty($search['name'])) {
			$query->andFilterWhere(['like', 'house_name', $search['name']])
            ->orFilterWhere(['like', 'address', $search['name']]);
		
			$queryNum->andFilterWhere(['like', 'house_name', $search['name']])
            ->orFilterWhere(['like', 'address', $search['name']]);
        }
		
		$searchRegion = $search['region'];
        if (!empty($searchRegion) && $searchRegion>0) {
            if($search['region_type']=='1'){
                $query->andWhere(['region_id' => $searchRegion]);
				$queryNum->andWhere(['region_id' => $searchRegion]);
            }
            else{
                $rr = BaseRegionModel::find()->select(['id'])->where(['parent'=>$searchRegion])->asArray()->column();
                array_push($rr,$searchRegion);
                $query->andWhere(['in','region_id',$rr]);
				$queryNum->andWhere(['in','region_id',$rr]);
            }
        }

        if (!empty($search['price'])) {
            $unitPrice = BaseUnitPriceModel::findOne($search['price']);
            if (!empty($unitPrice)) {
                if (!empty($unitPrice->min_price)) {
                    $query->andWhere(['>', 'house_unit_price', $unitPrice->min_price]);
					$queryNum->andWhere(['>', 'house_unit_price', $unitPrice->min_price]);
                }
                if (!empty($unitPrice->max_price)) {
                    $query->andWhere(['<', 'house_unit_price', $unitPrice->max_price]);
					$queryNum->andWhere(['<', 'house_unit_price', $unitPrice->max_price]);
                }

            }
        }
        if (!empty($search['room'])) {
            $room = BaseHouseTypeModel::findOne($search['room']);
            if (!empty($room)) {
                $query->andWhere("room1<={$search['room']} && room2>={$search['room']}");
				$queryNum->andWhere("room1<={$search['room']} && room2>={$search['room']}");
            }

        }

        if (!empty($search['type'])) {
            $query->andWhere(["category_id" => $search['type']]);
			$queryNum->andWhere(["category_id" => $search['type']]);
        }
        

        $data = $query->asArray()->all();
		$dataNum = $queryNum->asArray()->all();
        if (count($data) > $pageSize) {
            unset($data[$pageSize]);
            $nextPage = $page + 1;
        }

        if (!empty($data)) {
            $hourseIds = ArrayHelper::getColumn($data, 'id');
            $images = HouseImageLogic::instance()->getFirstImage($hourseIds);

            foreach ($data as $k => $v) {
                $v['marks']=$this->getHouseMarks($v['id']);
                $v['img_path'] = empty($images[$v['id']]) ? '' : $images[$v['id']];
                $data[$k] = $v;
            }

        }

        return ['nextPage' => $nextPage,'pageNum'=>count($dataNum), 'list' => $data];
    }

    protected function getHouseMarks($house_id){
        $marks=BaseHouseMarkModel::find()->select("a.mark")->alias('a')->leftJoin('ph_house_mark b','b.mark_id=a.id')->where(['b.house_id'=>$house_id])->limit(5)->all();
        return ArrayHelper::getColumn($marks, 'mark');
    }

    public function houseSave(HouseModel $model)
    {
        $this->saveFile($model, 'banner');
        $this->saveFile($model, 'adv');
        if (!empty($model->building_type) && is_array($model->building_type)) {
            $type = $model->building_type;
            $model->building_type = join(',', $type);
        }


        if ($model->is_adv == 1) {
            $this->updateAdv();
        }

        $rs = $model->save();
        if($rs){
            $this->saveMarks($model);
        }

//        $rlt=$this->transaction(function (){
//            return true;
//        });
        return $rs;
    }

    protected function saveMarks($model){
        $hid = $model->attributes['id'];
        $houseMarkModel=new HouseMarkModel();

        if (!empty($hid)&&!empty($model->house_mark) && is_array($model->house_mark)) {
            $marks = $model->house_mark;

            $houseMarkModel::deleteAll(['house_id'=>$hid]);

            foreach ($marks as $key => $value) {
                $houseMarkModel=new HouseMarkModel();
                $houseMarkModel->house_id=$hid;
                $houseMarkModel->mark_id=$value;
                $houseMarkModel->save();
            }
        }
    }


    /**
     * 保存上传文件banner、广告位
     *
     * @param \common\models\HouseModel $model
     * @param                           $key
     */
    protected function saveFile(HouseModel $model, $key)
    {
        if ($_FILES && !empty($_FILES['HouseModel']['name'][$key])) {
            $filePath = "/upload/$key/";
            $fileName = $filePath . uniqid() . '.' . pathinfo($_FILES['HouseModel']['name'][$key], PATHINFO_EXTENSION);
            $filePath = \Yii::getAlias('@webroot') . $filePath;
            if (!file_exists($filePath)) {
                mkdir($filePath, 0777, true);
            }
            $savePath = \Yii::getAlias('@webroot') . $fileName;
            if (move_uploaded_file($_FILES['HouseModel']['tmp_name'][$key], $savePath)) {
                $model->$key = $fileName;
            }
        }
    }


    protected function updateAll($set, $where)
    {
        HouseModel::updateAll($set, $where);
    }

    public function updateAdv()
    {
        $this->updateAll(['is_adv' => 0], ['is_adv' => 1]);
    }


}